class CheckIn < ActiveRecord::Base
  Actions = ["initial_checkin", "pick_up", "transfer", "drop_off"]

  belongs_to :item
  validates_presence_of :item
  belongs_to :location
  validates_presence_of :location
  belongs_to :user
  validates_presence_of :user
 
  validates_presence_of :action 
  validates_inclusion_of :action, :in => Actions

  before_validation :check_in_contained_items, :unless => :is_dropoff?
  def check_in_contained_items
    if item and item.contained_items
      item.contained_items.each do |i|
        i.check_ins << CheckIn.new(:location => location,
                  :user => user,
                  :action => action)
      end
    end
  end
  
  def is_dropoff?
	action == "drop_off" or action == "initial_checkin"
  end
  
  after_save :update_item_status
  def update_item_status
    if item
      case action 
        when "drop_off" then item.delivered = true
        when "pick_up" then item.picked_up = true
      end
      item.save
    end
  end
  
  validate :valid_location
  def valid_location
    if action == "drop_off"
      if not location.id == item.destination.id
        errors.add_to_base("Item must be dropped off at the correct destination")
      end
    end
  end
end
